﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace Himp.Outpatient
{
    /// <summary>
    /// 门诊申请单详细
    /// </summary>
    public class OtpAppyFormDetlService : OutpatientAppService, IOtpAppyFormDetlService
    {
        private IRepository<OtpAppyFormDetl, Guid> _otpAppyFormDetlRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="OtpAppyFormRepository"></param>
        public OtpAppyFormDetlService(IRepository<OtpAppyFormDetl, Guid> otpAppyFormDetlRepository)
        {
            _otpAppyFormDetlRepository = otpAppyFormDetlRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<OtpAppyFormDetlDto>> GetListAsync(OtpAppyFormDetlInput input)
        {
            var iQuery = await _otpAppyFormDetlRepository.GetQueryableAsync();
            iQuery = iQuery.WhereIf(input.OtpAppyFormId != null, i => i.OtpAppyFormId == input.OtpAppyFormId);

            if (input.Pi == 0)
            {
                var itemsDto = ObjectMapper.Map<List<OtpAppyFormDetl>, List<OtpAppyFormDetlDto>>(iQuery.ToList());

                return new PagedResultDto<OtpAppyFormDetlDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = iQuery.Count();
                var items = iQuery.Page(input.Pi, input.Ps);
                var itemsDto = ObjectMapper.Map<List<OtpAppyFormDetl>, List<OtpAppyFormDetlDto>>(items.ToList());

                return new PagedResultDto<OtpAppyFormDetlDto>(totalCount, itemsDto);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<OtpAppyFormDetlDto> PostAsync(OtpAppyFormDetlCreateDto input)
        {
            var otpAppyForm = ObjectMapper.Map<OtpAppyFormDetlCreateDto, OtpAppyFormDetl>(input);
            otpAppyForm = await _otpAppyFormDetlRepository.InsertAsync(otpAppyForm);
            var itemDto = ObjectMapper.Map<OtpAppyFormDetl, OtpAppyFormDetlDto>(otpAppyForm);

            return itemDto;
        }
    }
}
